/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ec.edu.farmacia.interfaces;

import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Intel
 */
public class Proveedores extends javax.swing.JFrame {
    
    DefaultTableModel model;
    String nombreArchivo;
    private String  codigo;
    private String  nombre_lab;
    public Proveedores() {
        initComponents();
        cargarLaboratorio();
        txtProveNombre.setEnabled(false);
        cargarTablaProveedores("", "", "");
        
        tProveedores.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
              @Override
        public void valueChanged(ListSelectionEvent e) {
                                               
                  
                try{                     
                  
                if(tProveedores.getSelectedRow()!=-1){
                    int fila=tProveedores.getSelectedRow();
                   txtProveCedula.setText(tProveedores.getValueAt(fila,0).toString().trim());
                   txtProveNombre.setText(tProveedores.getValueAt(fila,1).toString().trim());
                   txtProveApellido.setText(tProveedores.getValueAt(fila,2).toString().trim());
                   txtProveDireccion.setText(tProveedores.getValueAt(fila,3).toString().trim());
                   txtProveTelefono.setText(tProveedores.getValueAt(fila,4).toString().trim());
                   txtRuta.setText(tProveedores.getValueAt(fila, 5).toString().trim());
                    ImageIcon logo=new ImageIcon(txtRuta.getText().trim());
                    Icon icono = new ImageIcon(logo.getImage().getScaledInstance(lbFoto.getWidth(), lbFoto.getHeight(), Image.SCALE_DEFAULT));
                    lbFoto.setIcon(icono);
                    CmbLaboratorio.setSelectedItem(tProveedores.getValueAt(fila,6).toString().trim());
                                        
                    btnGuardar.setEnabled(true);
                    btnActualizar.setEnabled(true);
                    txtProveCedula.setEnabled(false);
                }
          }catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error ::"+ex);
        }
                  
            }
        });
    }

    public Boolean validarcedula(String c1){
  c1=c1.trim();
  int sw=0;
  try
  { 
          
    if (c1.isEmpty()){
        //mensajes_error(" la cedula esta vacia...");
        txtProveCedula.requestFocus();
    }
    int l=c1.length();
    if ((l>10) || (l<10)){
        //mensajes_error(" la longitud de la cedula no es correcta.");
        txtProveCedula.requestFocus();
    }
    if (!c1.matches("^[0-9]{10}$")){
        //mensajes_error(" la cedula debe ser solo numeros.");
        txtProveCedula.requestFocus();
    }
    int v = Integer.parseInt(String.valueOf(c1.charAt(9)));
    int suma=0;                
    String c3;
            
    //c3= "antes de calcular::{"+c1+"{ longitud cadena:"+l+" valor pos 10  v: "+String.valueOf(v)+ " suma= "+String.valueOf(v);
    //mensajes_error(c3);
    
    for (int i = 0; i<=8; i++){
        int valor = Integer.parseInt(String.valueOf(c1.charAt(i)));        
        int j=i+1;
        if (!enteroespar(j)){
            valor=valor*2;
            if (valor >9){
                valor=valor-9;
            }
        }
        suma=suma+valor;        
    }
    int verifica = 10-(suma -(suma/10)*10);
    if (verifica==10){
        verifica=0;
    }
    //c3= "calculado verificador:"+String.valueOf(verifica)+" valor pos 10  v: "+String.valueOf(v)+ " suma= "+String.valueOf(suma);
    //mensajes_error(c3);
    if(verifica != v){
       //JOptionPane.showMessageDialog(null, "La cedula esta incorrecta");
        sw=1;
        //txtAluCelda.requestFocus();
    }    
  } 
   catch (NumberFormatException nfe) 
  {
    //mensajes_error("Una excepcion ocurrio en el proceso de validadcion");
    return false;
  } 
     catch (Exception err) 
  {
     //mensajes_error("Una excepcion ocurrio en el proceso de validadcion");
     return false;       
  }
  
  if (sw==1){
      return false;
  } else {
      return true;
  }
        
    
}

public Boolean enteroespar(int v1){
    if (((v1/2)*2)!=v1){
        return false;
    }
    return true;
}

 public void CopiarFicheros (String dirOrigen, String dirDestino){      
                File origen = new File(dirOrigen);
                File destino = new File(dirDestino);
                
                try {
                        InputStream in = new FileInputStream(origen);
                        OutputStream out = new FileOutputStream(destino);
                                
                        byte[] buf = new byte[1024];
                        int len;

                        while ((len = in.read(buf)) > 0) {
                                out.write(buf, 0, len);
                        }
                
                        in.close();
                        out.close();
                } catch (IOException ioe){
                        ioe.printStackTrace();
                        //JOptionPane.showMessageDialog(rootPane, "Ha ocurrido un error");
                }
               
}
 public void cargarLaboratorio(){
           try {
                 //cbEstCivil.removeAllItems();
               conexion cc=new conexion();
               Connection cn=cc.conectar();
               String sql="";
               sql="Select *from laboratorio ";
               Statement st=cn.createStatement();
               ResultSet rs=st.executeQuery(sql);
               while(rs.next()){
                   codigo=rs.getString("LAB_CODIGO");
                   nombre_lab =rs.getString("LAB_NOMBRE");
                   CmbLaboratorio.addItem(nombre_lab);
                   
                   
               }          } catch (SQLException ex) {
               Logger.getLogger(Proveedores.class.getName()).log(Level.SEVERE, null, ex);
           }
    }
public void cargarCodLab(){
     txtProveCodLab.setEnabled(false);
        String sql ="select LAB_CODIGO from LABORATORIO";
        if (!(CmbLaboratorio.getSelectedIndex()==0)){
            sql="select LAB_CODIGO from LABORATORIO where LAB_NOMBRE = '"+CmbLaboratorio.getSelectedItem()+"';";
        }
            
        try {
            conexion cc=new conexion();
            Connection cn=cc.conectar();            
            Statement psw = cn.createStatement();
            ResultSet rs = psw.executeQuery(sql);
            rs.next();
            txtProveCodLab.setText(rs.getString("LAB_CODIGO"));
            
            
        } catch (SQLException ex) {
            //Logger.getLogger(Materias.class.getName()).log(Level.SEVERE, null, ex);
            //JOptionPane.showMessageDialog(null, ex);            
        }
}
public void guardarProveedor()
            
    {
        if(txtProveCedula.getText().trim().isEmpty())
        {
            JOptionPane.showMessageDialog(null, "no puede ingresar proveedor sin cédula");            
            txtProveCedula.requestFocus();
        }
        else{
          if(txtProveNombre.getText().trim().isEmpty()){
              JOptionPane.showMessageDialog(null, "no puede ingresar proveedor sin nombre");
            txtProveNombre.requestFocus();
              
          }
           if(txtProveApellido.getText().trim().isEmpty()){
              JOptionPane.showMessageDialog(null, "no puede ingresar proveedor sin apellido");
            txtProveApellido.requestFocus();   
          }
           else
           {
           
                if(txtProveTelefono.getText().trim().isEmpty()){
              JOptionPane.showMessageDialog(null, "no puede ingresar proveedor sin telefono");
            txtProveTelefono.requestFocus();
            }
                else{
                             
            if(txtProveDireccion.getText().trim().isEmpty()){
              JOptionPane.showMessageDialog(null, "no puede ingresar proveedor sin direccion");
            txtProveDireccion.requestFocus();
              
          }
        
        else{
                           
        conexion cc= new conexion();
                Connection cn = cc.conectar();
                String prove_cedula,prove_nombre,prove_apellido,prove_direccion,prove_telefono,cod_lab;
                String sql="";
                prove_cedula=txtProveCedula.getText();
                prove_nombre=txtProveNombre.getText();
                prove_apellido=txtProveApellido.getText();
                prove_direccion=txtProveDireccion.getText();
                prove_telefono=txtProveTelefono.getText();
                  String nombre=txtProveApellido.getText()+txtProveNombre.getText();
               String dirDest="src/imagenes/"+nombre+".jpg"; 
               cod_lab=txtProveCodLab.getText();
                  
             //JOptionPane.showMessageDialog(this, sql);                             
              sql="insert into proveedores(PROVE_CEDULA, PROVE_NOMBRE, PROVE_APELLIDO,PROVE_DIRECCION,PROVE_TELEFONO,PROVE_FOTO,COD_LAB_VEN) values(?,?,?,?,?,?,?)";
         try {
                PreparedStatement psw= cn.prepareStatement(sql);
                psw.setString(1, prove_cedula);
                psw.setString(2, prove_nombre);
                psw.setString(3, prove_apellido);
                psw.setString(4, prove_direccion);                
                psw.setString(5, prove_telefono);
                psw.setString(6, dirDest);
                psw.setString(7, cod_lab);
                int n= psw.executeUpdate();// el execute Update devuelve un numero entero debuelve cero si no insertas nada y uno si se inserto
                if(n>0)//si  se inserto
                {
                     CopiarFicheros(txtRuta.getText(),dirDest);
                  JOptionPane.showMessageDialog(null, "Se grabo correctamente");
                    cargarTablaProveedores("","","");
                  
                  btnNuevo.setEnabled(true);
                  btnGuardar.setEnabled(true);
                }
                
        } catch (SQLException ex) {
            
            JOptionPane.showMessageDialog(null, "No se grabo...." +ex);
       } 
       }
       }
      }
    }
        }
public void ocultarColu(){
         tProveedores.getColumnModel().getColumn(5).setMaxWidth(0);
         tProveedores.getColumnModel().getColumn(5).setMinWidth(0);
         tProveedores.getTableHeader().getColumnModel().getColumn(5).setMaxWidth(0); 
         tProveedores.getTableHeader().getColumnModel().getColumn(5).setMinWidth(0);
    }
  public void cargarTablaProveedores(String Dato,String nombre,String apellido){
        String[] titulos ={"CEDULA","NOMBRE","APELLIDO","DIRECCION","TELEFONO","","LABORATORIO"};
        String []registros=new String[8];
        String sql;
        conexion cc=new conexion();
        Connection cn=cc.conectar();
        
        //sql="select alu_cedula,alu_nombre,alu_apellido,alu_direccion,alu_fecha,alu_telefono,alu_foto,estadocivildescripcion from alumnos,estado_civil Where ALU_CEDULA LIKE '%" +Dato+"%' and ALU_NOMBRE LIKE '" +nombre+"%' AND " + " alu_apellido like '"+apellido+"%' order by ALU_CEDULA,ALU_NOMBRE AND ALU_APELLIDO and alumnos.id_est=estado_civil.id_est";
        sql="select prove_cedula,prove_nombre,prove_apellido,prove_direccion,prove_telefono,prove_foto,lab_nombre from proveedores,laboratorio Where proveedores.cod_lab_ven=laboratorio.lab_codigo and PROVE_CEDULA LIKE '%" +Dato+"%' and PROVE_NOMBRE LIKE '" +nombre+"%' AND " + " PROVE_apellido like '"+apellido+"%' order by PROVE_CEDULA,PROVE_NOMBRE AND PROVE_APELLIDO ";
        model=new DefaultTableModel(null,titulos);
        
        try {
            Statement st=cn.createStatement();
            ResultSet rs=st.executeQuery(sql);
             
            while(rs.next()){
                registros[0]=rs.getString("PROVE_CEDULA");
                registros[1]=rs.getString("PROVE_NOMBRE");
                registros[2]=rs.getString("PROVE_APELLIDO");
                registros[3]=rs.getString("PROVE_DIRECCION");                
                registros[4]=rs.getString("PROVE_TELEFONO");
                registros[5]=rs.getString("PROVE_FOTO");
                registros[6]=rs.getString("LAB_NOMBRE");
               // registros[7]=rs.getString("estadocivildescripcion");
                
                
                model.addRow(registros);
            }
            tProveedores.setModel(model);
            ocultarColu();            
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null,"LA TABLA TIENE PROBLEMAS AL CARGARSE"+ex);
        }
        
        }
  public void actualizar(){
      txtProveCedula.setEnabled(false);
      txtProveNombre.setEnabled(true);
        conexion cc=new conexion();
        Connection cn=cc.conectar();
        String sql="";        
         String direc;        
             if(!txtRuta.getText().startsWith("src/imagenes/") ){
          direc="src/imagenes/"+nombreArchivo;
          
         } else{
             direc=txtRuta.getText().trim();
         }
         sql="update PROVEEDORES SET PROVE_NOMBRE='"+txtProveNombre.getText()+
                 "',PROVE_APELLIDO='"+txtProveApellido.getText()+
                 "',PROVE_DIRECCION='"+txtProveDireccion.getText()+
                 "',PROVE_TELEFONO='"+txtProveTelefono.getText()+
                 "',PROVE_FOTO='"+direc+"'"+
                 ", COD_LAB_VEN='"+txtProveCodLab.getText()+
                 "' where PROVE_CEDULA='"+txtProveCedula.getText()+"'";
       try {
            PreparedStatement psw =cn.prepareStatement(sql);
            int n=psw.executeUpdate();
            if(n>0){
                JOptionPane.showMessageDialog(null, "Se actualizo correctamente");
                 if(!txtRuta.getText().startsWith("src/imagenes/") ){
                    CopiarFicheros(txtRuta.getText(),direc); 
                    }
           
		cargarTablaProveedores("","","");
                btnActualizar.setEnabled(false);
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null,"No se actualizo" +ex);
        }
        
    }
public void  borrar(){
         if(JOptionPane.showConfirmDialog(new JFrame(),
          "Esta seguro de Eliminar el registro","Borrar registro",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
 
       conexion cc=new conexion();
        Connection cn=cc.conectar();
        String sql="";
        sql="delete from proveedores where prove_cedula='"+txtProveCedula.getText()+"'";
                try{
                  PreparedStatement psw=cn.prepareStatement(sql);
                  int n=psw.executeUpdate();
                  if(n>0)
                  {
                      JOptionPane.showMessageDialog(null,"Se elimino correctamente");
                      cargarTablaProveedores("","","");
                      
                  }
                    
                }catch(SQLException ex){
                    JOptionPane.showMessageDialog(null,"NO se elimino");
                }
    }
         
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtProveCedula = new javax.swing.JTextField();
        txtProveNombre = new javax.swing.JTextField();
        txtProveApellido = new javax.swing.JTextField();
        txtProveDireccion = new javax.swing.JTextField();
        txtProveCodLab = new javax.swing.JTextField();
        txtProveTelefono = new javax.swing.JTextField();
        CmbLaboratorio = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        btnNuevo = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnActualizar = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        lbFoto = new javax.swing.JLabel();
        txtRuta = new javax.swing.JTextField();
        btnCargarFoto = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tProveedores = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("CÉDULA");

        jLabel2.setText("NOMBRE");

        jLabel3.setText("APELLIDO");

        jLabel4.setText("DIRECCION");

        jLabel5.setText("TELEFONO");

        jLabel6.setText("LABORATORIO");

        txtProveCedula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtProveCedulaActionPerformed(evt);
            }
        });
        txtProveCedula.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtProveCedulaFocusLost(evt);
            }
        });
        txtProveCedula.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtProveCedulaKeyTyped(evt);
            }
        });

        txtProveNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtProveNombreActionPerformed(evt);
            }
        });
        txtProveNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtProveNombreKeyTyped(evt);
            }
        });

        txtProveApellido.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtProveApellidoActionPerformed(evt);
            }
        });
        txtProveApellido.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtProveApellidoKeyTyped(evt);
            }
        });

        txtProveDireccion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtProveDireccionActionPerformed(evt);
            }
        });
        txtProveDireccion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtProveDireccionKeyTyped(evt);
            }
        });

        txtProveTelefono.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtProveTelefonoKeyTyped(evt);
            }
        });

        CmbLaboratorio.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                CmbLaboratorioItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtProveCedula)
                            .addComponent(txtProveNombre)
                            .addComponent(txtProveApellido)
                            .addComponent(txtProveDireccion)
                            .addComponent(txtProveTelefono, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE))
                        .addGap(28, 28, 28))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(CmbLaboratorio, 0, 99, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtProveCodLab, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtProveCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtProveNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(txtProveApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtProveDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtProveTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtProveCodLab, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CmbLaboratorio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(30, Short.MAX_VALUE))
        );

        btnNuevo.setText("NUEVO");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnGuardar.setText("GUARDAR");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnEliminar.setText("ELIMINAR");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnActualizar.setText("ACTUALIZAR");
        btnActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 33, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnActualizar)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(btnNuevo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)
                        .addComponent(btnEliminar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnNuevo)
                .addGap(18, 18, 18)
                .addComponent(btnGuardar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnEliminar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnActualizar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel7.setFont(new java.awt.Font("Times New Roman", 2, 14)); // NOI18N
        jLabel7.setForeground(new java.awt.Color(51, 0, 204));
        jLabel7.setText("PROVEEDORES");

        lbFoto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                lbFotoKeyReleased(evt);
            }
        });

        txtRuta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtRutaActionPerformed(evt);
            }
        });

        btnCargarFoto.setText("FOTO");
        btnCargarFoto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCargarFotoActionPerformed(evt);
            }
        });

        tProveedores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tProveedores);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(230, 230, 230)
                                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 94, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(lbFoto, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtRuta, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(btnCargarFoto)
                                        .addGap(33, 33, 33)))
                                .addGap(74, 74, 74)))
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbFoto, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30)
                        .addComponent(txtRuta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(7, 7, 7)
                        .addComponent(btnCargarFoto))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(52, 52, 52))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtProveCedulaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtProveCedulaKeyTyped
        char car = evt.getKeyChar();
        if(txtProveCedula.getText().length()>=10) evt.consume();
        if((car<'0' || car>'9')) evt.consume();
    }//GEN-LAST:event_txtProveCedulaKeyTyped

    private void txtProveNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtProveNombreKeyTyped
        txtProveNombre.setText(txtProveNombre.getText().toUpperCase());
        char car = evt.getKeyChar();
        if(txtProveNombre.getText().length()>=30) evt.consume();        
       if ((car<'a' || car>'z' ))
           evt.consume();
    }//GEN-LAST:event_txtProveNombreKeyTyped

    private void txtProveApellidoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtProveApellidoKeyTyped
        txtProveApellido.setText(txtProveApellido.getText().toUpperCase());
        char car = evt.getKeyChar();
        if(txtProveApellido.getText().length()>=30) evt.consume();        
       if ((car<'a' || car>'z' ))
           evt.consume();
    }//GEN-LAST:event_txtProveApellidoKeyTyped

    private void txtProveDireccionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtProveDireccionKeyTyped
      /*  txtProveDireccion.setText(txtProveDireccion.getText().toUpperCase());
        char car = evt.getKeyChar();
        if(txtProveDireccion.getText().length()>=30) evt.consume();
            if ((car<'a' || car>'z' ))
           evt.consume();*/
    }//GEN-LAST:event_txtProveDireccionKeyTyped

    private void txtProveTelefonoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtProveTelefonoKeyTyped
       char car = evt.getKeyChar();
        if(txtProveTelefono.getText().length()>=10) evt.consume();
             if((car<'0' || car>'9')) evt.consume();
    }//GEN-LAST:event_txtProveTelefonoKeyTyped

    private void txtProveCedulaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtProveCedulaFocusLost
       String cadena = txtProveCedula.getText().trim();    
    if (cadena.isEmpty() || cadena.length()==0 ){
               txtProveCedula.requestFocus();        
    }         
    else 
    {
        if (validarcedula(cadena)){
            txtProveNombre.setEnabled(true);
            txtProveNombre.requestFocus();           
        }
       
                      
    }
    }//GEN-LAST:event_txtProveCedulaFocusLost

    private void txtProveCedulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtProveCedulaActionPerformed
        txtProveNombre.requestFocus();
    }//GEN-LAST:event_txtProveCedulaActionPerformed

    private void txtProveNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtProveNombreActionPerformed
        txtProveApellido.requestFocus();
    }//GEN-LAST:event_txtProveNombreActionPerformed

    private void txtProveApellidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtProveApellidoActionPerformed
       txtProveDireccion.requestFocus();
    }//GEN-LAST:event_txtProveApellidoActionPerformed

    private void txtProveDireccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtProveDireccionActionPerformed
       txtProveTelefono.requestFocus();
    }//GEN-LAST:event_txtProveDireccionActionPerformed

    private void lbFotoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_lbFotoKeyReleased

    }//GEN-LAST:event_lbFotoKeyReleased

    private void txtRutaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtRutaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtRutaActionPerformed

    private void btnCargarFotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCargarFotoActionPerformed
        JFileChooser dir = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "imagenes", "jpg", "gif","png","bmp");
        dir.setFileFilter(filter);
        int op = dir.showOpenDialog(this);
        if (op == JFileChooser.APPROVE_OPTION) {
            String direccion = dir.getSelectedFile().getAbsolutePath();
            ImageIcon logo=new ImageIcon(direccion);
            Icon icono = new ImageIcon(logo.getImage().getScaledInstance(lbFoto.getWidth(), lbFoto.getHeight(), Image.SCALE_DEFAULT));
            lbFoto.setIcon(icono);
            txtRuta.setText(direccion);
            nombreArchivo=dir.getSelectedFile().getName();
        }
    }//GEN-LAST:event_btnCargarFotoActionPerformed

    private void CmbLaboratorioItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_CmbLaboratorioItemStateChanged
         cargarCodLab();
    }//GEN-LAST:event_CmbLaboratorioItemStateChanged

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        guardarProveedor();
         
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarActionPerformed
        actualizar();
    }//GEN-LAST:event_btnActualizarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
       borrar();
    }//GEN-LAST:event_btnEliminarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Proveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Proveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Proveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Proveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Proveedores().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox CmbLaboratorio;
    private javax.swing.JButton btnActualizar;
    private javax.swing.JButton btnCargarFoto;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbFoto;
    private javax.swing.JTable tProveedores;
    private javax.swing.JTextField txtProveApellido;
    private javax.swing.JTextField txtProveCedula;
    private javax.swing.JTextField txtProveCodLab;
    private javax.swing.JTextField txtProveDireccion;
    private javax.swing.JTextField txtProveNombre;
    private javax.swing.JTextField txtProveTelefono;
    private javax.swing.JTextField txtRuta;
    // End of variables declaration//GEN-END:variables
}
